package com.zh.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatisplus自动填充实体字段
 * @author ZH
 * @date 22:01 2021/11/16
 */
@Component
@Slf4j
public class MyBatisAuditorHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.trace("start insert fill ....");
        var username = "system";
        // 起始版本 3.3.0(推荐使用)
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());

        if (metaObject.hasSetter("creator")) {
            this.strictInsertFill(metaObject, "creator", String.class, username);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.trace("start update fill ....");
        var username = "system";
        // 起始版本 3.3.0(推荐)
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        if (metaObject.hasSetter("updater")) {
            this.strictUpdateFill(metaObject, "updater", String.class, username);
        }
    }
}
